package com.etonenet.util;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil<T> {

	protected static ObjectMapper mapper = new ObjectMapper();

	/**
	 * @Description 对象转换成json
	 * @param obj
	 * @return
	 * @throws Exception
	 * @author zhangleyu@139.com
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 * @time 2011-11-11 下午4:59:09
	 */
	public static String objectToJson(Object obj) {

		try {
			return mapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new RuntimeException("objectToJson err:" + e.getMessage());
		}

	}

	/**
	 * @Description json转换成对象
	 * @param content
	 * @param clazz
	 * @return
	 * @throws Exception
	 * @author zhangleyu@139.com
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * @time 2011-11-11 下午5:26:04
	 */
	public static <T> T jsonToObject(String content, Class<T> valueType) {

		try {
			return mapper.readValue(content, valueType);
		} catch (Exception e) {
			throw new RuntimeException("objectToJson Class<T> valueType err:" + e.getMessage());
		}
	}

	/**
	 * @Description json转换成对象
	 * @param content
	 * @param reference
	 * @return
	 * @throws Exception
	 * @author zhangleyu@139.com
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * @time 2011-11-24 下午1:29:18
	 */
	public static <T> T jsonToObject(String content, TypeReference<T> reference) {

		try {
			return mapper.readValue(content, reference);
		} catch (Exception e) {
			throw new RuntimeException("objectToJson TypeReference<T> reference err:" + e.getMessage());
		}
	}

}
